import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import useAssistantListStore from "@/stores/assistantList";
import { list_chat_dialogs, rename_chat_dialog, delete_chat_dialog } from "@/api/chat";
import { v4 as uuidv4 } from 'uuid';
import { CODE } from "@/api/constants";
import { result } from "@/utils/result";
import { now_seconds } from "@/utils/time";

export const INVALID_CHAT_ID = "";

const useChatListStore = defineStore('chat-list', () => {
    const chatDialogs = ref([])
    const isEmpty = computed(() => {
        return chatDialogs.value.length === 0
    })
    const pushDia = (dia) => {
        chatDialogs.value.unshift(dia);
    }
    const getDia = (id) => {
        const index = chatDialogs.value.findIndex(item => item.id === id);
        if (index === -1) {
            return undefined;
        }
        return chatDialogs.value[index];
    }
    const deleteDia = (dia) => {
        const index = chatDialogs.value.findIndex(item => item.id === dia.id);
        if (index !== -1) {
            chatDialogs.value.splice(index, 1);
        }
    }
    const updateDia = (updatedDia) => {
        const index = chatDialogs.value.findIndex(item => item.id === updatedDia.id);
        if (index !== -1) {
            chatDialogs.value.splice(index, 1, updatedDia);
        }
    }
    const topDia = (dia) => {
        if (chatDialogs.value.length > 0 && chatDialogs.value[0].id !== dia.id) {
            deleteDia(dia)
            pushDia(dia)
        }
    }

    const activeChatDia = ref(null)
    const isSelectActiveDia = computed(() => {
        return !!activeChatDia.value
    })
    const setActiveDia = (dia) => {
        activeChatDia.value = dia
    }

    const canCreatDialog = computed(() => {
        return useAssistantListStore().isSelectActiveAssistant
    })
    const createDialog = (name) => {
        const dia = {
            id: INVALID_CHAT_ID,
            name: name,
            lastActiveAt: now_seconds(),
            assistantId: useAssistantListStore().activeAssistantId, 
            requestId: uuidv4(),
        }
        deleteDia(dia) // 保证 INVALID_CHAT_ID 的会话只有一个
        pushDia(dia)
    }

    // 聊天记录列表获取
    const defaultOnList = (resp) => {
        console.info(resp)
    }
    let onList = defaultOnList
    const registerOnList = (callback) => {
        onList = callback
    }
    const unregisterOnList = () => {
        onList = defaultOnList
    }
    watch(
        [
            () => useAssistantListStore().activeAssistantId, 
            () => useAssistantListStore().isSelectActiveAssistant
        ],
        async ([newAssistantId, newIsActive], [oldAssistantId, oldIsActive]) => {
            setActiveDia(null)
            if (!newIsActive) {
                chatDialogs.value = []
                return
            }
            if (oldAssistantId !== newIsActive) {
                const resp = await list_chat_dialogs({ assistantId: newAssistantId })
                onList && onList(resp)
                chatDialogs.value = resp.data.dialogs
            }
        }
    )

    const renameDialog = async (id, newName) => {
        let dia = getDia(id)
        dia.name = newName
        if (id === INVALID_CHAT_ID) {
            return result(true, "重命名成功")
        }
        const resp = await rename_chat_dialog({ chatDialog: dia, newName: newName, requestId: uuidv4() })
        const isSuccess = resp.code === CODE.OK
        return result(isSuccess, isSuccess ? "重命名成功" : resp.msg)
    }

    const deleteDialog = async (id) => {
        const dia = getDia(id)
        deleteDia(dia)
        const resp = await delete_chat_dialog({ dialogId: dia.id })
        const isSuccess = resp.code === CODE.OK
        return result(isSuccess, isSuccess ? "删除成功" : resp.msg)
    }

    return { chatDialogs, canCreatDialog, isEmpty, activeChatDia, isSelectActiveDia, setActiveDia,
        registerOnList, unregisterOnList, createDialog, renameDialog, deleteDialog, topDia }
})

export default useChatListStore;